package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.atguigu.lease.common.jwt.JwtUtil.parseToken;

@Service
public class LoginServiceImpl implements LoginService {

@Autowired
private RedisTemplate redisTemplate;
@Autowired
private UserInfoService userInfoService;
    @Override
    public void sendCode(String phone) {
        String key= RedisConstant.APP_LOGIN_PREFIX+phone;
        //查询redis里是否有该键
        Boolean hashKey=redisTemplate.hasKey(key);

        if(hashKey){
            //redis中验证码过期时间
            Long expire=redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //RedisConstant中的验证码过期时间
            Integer appLoginCodeTTL= RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //获取验证码重新发送的时间限制
            Integer appLoginCodeResendTime= RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC;
            //检查手机号是否已经发送，并在有效期内，在的话，告诉她发送频繁
            if(appLoginCodeTTL-expire<appLoginCodeResendTime){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }

        }
        //生成验证码,6位数字
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<6;i++){
            sb.append((int)(Math.random()*10));
        }
        String code=sb.toString();
        System.out.println("验证码="+code);
        //存储在redis中
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {
        //接收前端验证码和手机号
        String key=RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        String code=(String) redisTemplate.opsForValue().get(key);
        //对比验证码是否正确
        if(code==null||!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //正确：判断数据库是否有此数据
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        //没有去注册
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("https://cn.bing.com/images/search?view=detailV2&ccid=53MKhh4k&id=5035DC0F0EAF6FD4D2B7514D80271F67A02DF0D8&thid=OIP.53MKhh4kao-JawcU7uKiiQHaLH&mediaurl=https%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202112%2F31%2F20211231053430_bdf21.jpg&exph=1600&expw=1066&q=%E5%94%90%E8%89%BA%E6%98%95&simid=608050057546629138&FORM=IRPRST&ck=EAA433E19C2B09FCD62E495BC0B5DA07&selectedIndex=2&itb=0&cw=1375&ch=758&ajaxhist=0&ajaxserp=0");
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //判断用户是否可用
        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //jwt生成token放回
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }

    @Override
    public UserInfoVo info(String accessToken) {

        //解析token,获取userId
        Integer userId =(Integer) JwtUtil.parseToken(accessToken).get("userId");
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
         return userInfoVo;
    }


}
